package main

import (
	"context"
	"log"
	"net/http"
	"os"
	"os/signal"
	"short-link/internal/job"
	"short-link/internal/router"
	"short-link/pkg"
	"syscall"
	"time"
)

func main() {
	start()
}

func start() {
	// load env config
	config := pkg.ReadConfig()

	// connect database
	db := pkg.ConnectToMySQL(&config.Mysql)
	// connect redis
	pkg.ConnectToRedis(&config.Redis)

	// Start the cleanup task
	go job.ClearExpiresURLs(db)

	// init router
	router.Init()
	r := router.Router

	// graceful shutdown
	server := &http.Server{
		Addr:    config.Server.Port,
		Handler: r,
	}

	log.Printf("👻 Server is now listening at port:  %s\n", config.Server.Port)

	go func() {
		if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			log.Fatalf("server listen error: %s\n", err)
		}
	}()

	quit := make(chan os.Signal, 1)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	i := <-quit
	log.Println("server receive a signal: ", i.String())

	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	if err := server.Shutdown(ctx); err != nil {
		log.Fatalf("server shutdown error: %s\n", err)
	}
	log.Println("Server exiting")
}
